//
//  ScanViewController.m
//  POS
//
//  Created by sigma xu on 4/17/13.
//  Copyright (c) 2013 sigma xu. All rights reserved.
//

#import "ScanVC.h"

@interface ScanVC ()

@end

@implementation ScanVC

@synthesize so_id, barcode,product_name,product_brand,quantity,unit_display,product_package,price,sv_item_list,total_amount,new_client_flag, suspendDisplayInfo;

bool scanActive=false;
NSTimer *ledTimer=nil;

-(IBAction)button_number:(id)sender{
    UIButton *button = (UIButton *)sender;
    int new_value = [quantity.text integerValue]*10+[button.titleLabel.text integerValue];
    if (new_value<=max_quantity) {
        quantity.text = [[NSString alloc]initWithFormat:@"%d",new_value];
    }
}
-(IBAction)button_delete{
    int new_value = [quantity.text integerValue]/10;
    if (new_value>0) {
        quantity.text = [[NSString alloc]initWithFormat:@"%d",new_value];
    }else{
        quantity.text = @"0";
    }
}
-(IBAction)button_unit{
    if ([unit_display.text isEqualToString:@"CS"]) {
        unit_display.text=@"EA";
        
    }else{
        unit_display.text=@"CS";
    }
    [self barcode_input];
}
-(IBAction)button_order{
    if (sv_item_list.count!=0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                       message: @"Please Enter Remark for Sales Order"
                                                      delegate: self
                                             cancelButtonTitle:@"Cancel"
                                             otherButtonTitles:@"Confirm",nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        alert.tag = 4;
        [alert show];
    }else if(sv_item_list.count==0){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                       message: @"This is a empty order"
                                                      delegate: self
                                             cancelButtonTitle:@"Cancel"
                                             otherButtonTitles:nil];
        [alert show];
    }
}
-(IBAction)button_reset{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Alert"
                                                   message: @"Are you sure you wanna reset"
                                                  delegate: self
                                         cancelButtonTitle:@"Cancel"
                                         otherButtonTitles:@"Confirm",nil];
    
    alert.tag = 5;
    [alert show];
}
-(IBAction)button_OK{
    //||[product_name.text isEqualToString:@"Product Name"]
    if ([self.title isEqualToString:@"New Client"]&&new_client_flag) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Alert"
                                                       message: @"Are you sure this is a New Client"
                                                      delegate: self
                                             cancelButtonTitle:@"Cancel"
                                             otherButtonTitles:@"Confirm",nil];
        
        alert.tag = 3;
        [alert show];
    }else if([barcode.text isEqualToString:@""]){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Warning"
                                                       message: @"There is no item has been scanned"
                                                      delegate: self
                                             cancelButtonTitle:@"Scan Again"
                                             otherButtonTitles:nil];
        
        alert.tag = 1;
        [alert show];
    }else if([self check_item_in_solist]>=0){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Alert"
                                                       message: @"This product has already been scanned"
                                                      delegate: self
                                             cancelButtonTitle:@"Cancel"
                                             otherButtonTitles:@"Update",@"Delete",nil];
        
        alert.tag = 2;
        [alert show];
    }else{
        [self add_item_solist];
    }
    
}
- (IBAction)barcode_input{
    ItemDBO *idbo = [[ItemDBO alloc] init];
    idbo = [idbo get_item_by_barcode:barcode.text unit_code:unit_display.text];
    if (idbo==NULL) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                       message: @"There is no such product in system"
                                                      delegate: self
                                             cancelButtonTitle:@"Scan Again"
                                             otherButtonTitles:nil];
        [alert show];
    }else{
        product_name.text = idbo.item_name;
        product_brand.text = idbo.item_brand;
        double price_double = [idbo.unit_price doubleValue];
        NSString *price_string = [[NSString alloc] initWithFormat:@"%.4f",price_double];
        price.text = [[NSString alloc]initWithFormat:@"$ %@",price_string];
        unit_display.text = idbo.unit;
        product_package.text = idbo.item_package;
    }
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    //OK button Click and no item been scanned
    if (alertView.tag == 1) {
        if (buttonIndex == 0) {
            //cancell
        }else if(buttonIndex == 1){
            //ok
        }
        //OK button Click and the item has already been scanned
    }else if(alertView.tag == 2){
        if (buttonIndex == 0) {
            //cancell
        }else if(buttonIndex == 1){
            //update
            ItemDBO *idbo = [sv_item_list objectAtIndex:[self check_item_in_solist]];
            barcode.text=idbo.item_barcode;
            product_name.text=idbo.item_name;
            price.text=[[NSString alloc]initWithFormat:@"$ %@",idbo.unit_price];
            quantity.text=[[NSString alloc]initWithFormat:@"%@",idbo.quantity];
            unit_display.text=idbo.unit;
            product_package.text=idbo.item_package;
            [self remove_item_solist];
        }else if(buttonIndex == 2){
            //delete
            [self remove_item_solist];
            barcode.text=@"";
            product_brand.text=@"Product Brand";
            product_name.text=@"Product Name";
            price.text=@"$ 0";
            quantity.text=@"0";
            unit_display.text=@"CS";
//            unichar chr[1] = {'\n'};
//            NSString *LineBreak = [NSString stringWithCharacters:(const unichar *)chr length:1];
            product_package.text=[NSString stringWithFormat:@"Package Size :"];
        }
        //OK button Click and this is a New Client
    }else if (alertView.tag == 3) {
        if (buttonIndex == 0) {
            //cancell
        }else if(buttonIndex == 1){
            //ok
            new_client_flag = FALSE;
            [self add_item_solist];
        }
    }else if (alertView.tag == 4) {
        if (buttonIndex == 0) {
            //cancell
        }else if(buttonIndex == 1){
            //ok
            remark = [alertView textFieldAtIndex:0].text;
            [self mark_order];
            [self viewDidLoad];
        }
    }else if (alertView.tag == 5) {
        //reset button
        if (buttonIndex == 0) {
            //cancell
        }else if(buttonIndex == 1){
            //ok
            [self viewDidLoad];
        }
    }
}
-(void)mark_order{
    SalesOrderDBO *sodbo = [[SalesOrderDBO alloc] init];
    //sodbo.so_id=so_id;
    //need to change this so_number with naming convention
    sodbo.so_number = [@"TEMP_" stringByAppendingString:self.title];
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    sodbo.sales_man = [prefs stringForKey:@"sales_man"];
    sodbo.total_amount = [[NSString alloc] initWithFormat:@"%.2f",total_amount];
    sodbo.total_item = [[NSString alloc] initWithFormat:@"%d",sv_item_list.count];
    sodbo.status = @"1";
    sodbo.client = self.title;
    sodbo.remark = remark;
    UINavigationController *nav = [self.tabBarController.viewControllers objectAtIndex:1];
    if ([so_id isEqualToString:@""]) {
        last_so_id = [sodbo insert_sales_order];
        for (int i=0; i<[sv_item_list count]; i++) {
            ItemDBO *idbo = [sv_item_list objectAtIndex:i];
            idbo.so_id=[NSString stringWithFormat:@"%d",last_so_id];
            [idbo check_update_so_item];
        }
        so_id = [[NSString alloc] initWithFormat:@"%d",last_so_id];
    }else{
        [sodbo update_sales_order];
        ItemDBO *idbo = [[ItemDBO alloc] init];
        idbo.so_id = so_id;
        [idbo delete_sales_order_each_item];
        for (int i=0; i<[sv_item_list count]; i++) {
            ItemDBO *idbo = [sv_item_list objectAtIndex:i];
            idbo.so_id=so_id;
            [idbo check_update_so_item];
        }
    }
    if ([nav.topViewController isKindOfClass:[SalesOrderDetailTVC class]]) {
        SalesOrderDetailTVC *sodtvc = (SalesOrderDetailTVC *)nav.topViewController;
        [sodtvc load_so_detail];
        [sodtvc.tableView reloadData];
    }
    ServiceConnector *sc = [[ServiceConnector alloc] init];
    [sc post_sales_order:so_id];
    SalesOrderTVC *sotvc = (SalesOrderTVC *)[nav.viewControllers objectAtIndex:0];
    [sotvc load_so_list];
    [sotvc.tableView reloadData];
    self.tabBarController.selectedIndex = 1;
}
-(void)remove_item_solist{
    [sv_item_list removeObjectAtIndex:[self check_item_in_solist]];
    [self calculate_total_amount];
}
-(int)check_item_in_solist{
    int item_index = -1;
    for(int i=0; i < [sv_item_list count]; i++){
        ItemDBO *idbo = [sv_item_list objectAtIndex:i];
        if ([idbo.item_barcode isEqualToString: barcode.text]) {
            item_index = i;
        }
    }
    return item_index;
}
-(void)add_item_solist{
    ItemDBO *idbo = [[ItemDBO alloc] init];
    idbo.item_barcode = barcode.text;
    idbo.item_name = product_name.text;
    idbo.item_package=product_package.text;
    idbo.quantity = quantity.text;
    idbo.unit = unit_display.text;
    idbo.unit_price =[price.text substringFromIndex:2];
    NSDate *datenow=[[NSDate alloc] init];
    NSDateFormatter *df_utc = [[NSDateFormatter alloc] init];
    [df_utc setTimeZone:[NSTimeZone localTimeZone]];
    [df_utc setDateFormat:@"yyy-MM-dd HH:mm:ss"];
    idbo.create_date = [df_utc stringFromDate:datenow];
    [sv_item_list insertObject:idbo atIndex:0];
//    [sv_item_list addObject:idbo];
    [self calculate_total_amount];
    quantity.text=@"0";
}
-(void)calculate_total_amount{
    total_amount = 0;
    for(int i=0; i < [sv_item_list count]; i++){
        ItemDBO *idbo = [sv_item_list objectAtIndex:i];
        total_amount = [idbo.unit_price doubleValue]*[idbo.quantity integerValue]+total_amount;
    }
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"sg_sc_il"]){
        ItemListTVC *iltvc = segue.destinationViewController;
        iltvc.title = [[NSString alloc]initWithFormat:@"$ %.2f",total_amount];
        iltvc.item_list=[[NSMutableArray alloc] init];
        iltvc.item_list = sv_item_list;
        iltvc.navigationItem.rightBarButtonItem = iltvc.editButtonItem;
    }
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    if(touch.tapCount >=1){
        [barcode resignFirstResponder];
        [price resignFirstResponder];
    }
}
-(void)ledTimerFunc:object
{
    if(![dtdev uiControlLEDsWithBitMask:arc4random() error:nil])
    {
        [ledTimer invalidate];
        ledTimer=nil;
    }
}
-(void)connectionState:(int)state {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//    [dateFormat setDateStyle:kCFDateFormatterLongStyle];
    
    [ledTimer invalidate];
    ledTimer=nil;
    
	switch (state) {
		case CONN_DISCONNECTED:
		case CONN_CONNECTING:
			[statusImage setImage:[UIImage imageNamed:@"disconnected.png"]];
			[displayText setText:[NSString stringWithFormat:@"Device not connected\nSDK: ver %d.%d (%@)",dtdev.sdkVersion/100,dtdev.sdkVersion%100,[dateFormat stringFromDate:dtdev.sdkBuildDate]]];
//			[batteryButton setHidden:TRUE];
//			[scanButton setHidden:TRUE];
//			[printButton setHidden:TRUE];
			break;
		case CONN_CONNECTED:
//            [debug deleteCharactersInRange:NSMakeRange(0,debug.length)];
//            debugText.text=@"";
            scanActive=false;
			[statusImage setImage:[UIImage imageNamed:@"connected.png"]];
			[status setString:[NSString stringWithFormat:@"SDK: ver %d.%d (%@)\n%@ %@ connected\nHardware revision: %@\nFirmware revision: %@\nSerial number: %@",dtdev.sdkVersion/100,dtdev.sdkVersion%100,[dateFormat stringFromDate:dtdev.sdkBuildDate],dtdev.deviceName,dtdev.deviceModel,dtdev.hardwareRevision,dtdev.firmwareRevision,dtdev.serialNumber]];
			[displayText setText:status];
//			[scanButton setHidden:FALSE];
//            if([dtdev getSupportedFeature:FEAT_BLUETOOTH error:nil]!=FEAT_UNSUPPORTED)
//                [printButton setHidden:FALSE];
            
//            [self updateBattery];
			break;
	}
}

-(void)deviceButtonPressed:(int)which {
    if([dtdev getSupportedFeature:FEAT_LEDS error:nil]==FEAT_SUPPORTED && ledTimer==nil)
    {
        ledTimer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(ledTimerFunc:) userInfo:nil repeats:YES];
    }
    
	[displayText setText:@""];
//	[statusImage setImage:[UIImage imageNamed:@"scanning.png"]];
}

-(void)deviceButtonReleased:(int)which {
    if([dtdev getSupportedFeature:FEAT_LEDS error:nil]==FEAT_SUPPORTED)
    {
        [ledTimer invalidate];
        ledTimer=nil;
        [dtdev uiControlLEDsWithBitMask:0 error:nil];
    }
//	[statusImage setImage:[UIImage imageNamed:@"connected.png"]];
}
-(void)barcodeData:(NSString *)barcode_scan isotype:(NSString *)isotype
{
//    mainTabBarController.selectedViewController=self;
    barcode.text=barcode_scan;
    [self barcode_input];
//	[status setString:@""];
//	[status appendFormat:@"ISO Type: %@\n",isotype];
//	[status appendFormat:@"Barcode: %@",barcode_scan];
//    
//	[displayText setText:status];
    
//	[self updateBattery];
}

-(void)barcodeData:(NSString *)barcode_scan type:(int)type
{
//    mainTabBarController.selectedViewController=self;
    barcode.text=barcode_scan;
    [self barcode_input];
//	[status setString:@""];
//    
//	[status appendFormat:@"Type: %d\n",type];
//	[status appendFormat:@"Type text: %@\n",[dtdev barcodeType2Text:type]];
//	[status appendFormat:@"Barcode: %@",barcode_scan];
//	[displayText setText:status];
    
    if([dtdev getSupportedFeature:FEAT_VIBRATION error:nil]==FEAT_SUPPORTED)
    {
        [dtdev uiEnableVibrationForTime:1.5 error:nil];
    }
    
//	[self updateBattery];
}


- (void)viewWillAppear:(BOOL)animated
{
	//update display according to current dtdev state
    if(!self.suspendDisplayInfo)
        [self connectionState:dtdev.connstate];
    self.suspendDisplayInfo=false;
}
- (void)viewDidLoad
{
    
    so_id=@"";
    barcode.text=@"";
    product_brand.text=@"Product Brand";
    product_name.text=@"Product Name";
    price.text=@"$ 0";
    quantity.text=@"0";
    unit_display.text=@"CS";
    product_package.text=@"Package Size :";
    total_amount = 0;
    new_client_flag = TRUE;
    max_quantity=99999999;
    sv_item_list=[[NSMutableArray alloc] init];
    self.title = @"New Client";
    dtdev=[DTDevices sharedDevice];
	[dtdev addDelegate:self];
    [dtdev connect];
    [self connectionState:dtdev.connstate];
    [super viewDidLoad];
}
#pragma mark -
#pragma mark Table view delegate


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
